//
//  ViewController.swift
//  iWeather
//
//  Created by 一川 on 6/9/15.
//  Copyright © 2015 huoteng. All rights reserved.
//

import UIKit
import CoreLocation

class ViewController: UIViewController, CLLocationManagerDelegate  {

    @IBOutlet weak var location: UILabel!
    
    @IBOutlet weak var icon: UIImageView!
    
    @IBOutlet weak var temperature: UILabel!
    
    @IBOutlet weak var loadingIndicator: UIActivityIndicatorView!
    
    @IBOutlet weak var loading: UILabel!

    
    let locationManager:CLLocationManager = CLLocationManager()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        loadingIndicator.startAnimating()
        locationManager.delegate = self
        // Do any additional setup after loading the view, typically from a nib.
        
        locationManager.desiredAccuracy = kCLLocationAccuracyBest
        
        if (ios8()) {
            locationManager.requestAlwaysAuthorization()
        }
        locationManager.startUpdatingLocation()
        
        let background = UIImage(named: "background_summer")
        self.view.backgroundColor = UIColor(patternImage: background!)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    func ios8()-> Bool {
        let version = UIDevice.currentDevice().systemVersion
        let ver = NSNumberFormatter().numberFromString(version)!.floatValue
        return ver >= 8.0
    }
    
    func locationManager(manager: CLLocationManager, didUpdateLocations locations: [AnyObject]) {
        let location:CLLocation = locations[locations.count - 1] as! CLLocation
        
        //if location changed, update weather info
        if (location.horizontalAccuracy > 0) {
            print(location.coordinate.latitude)
            print(location.coordinate.longitude)
            
            updateWeatherInfo(location.coordinate.latitude, longitude:location.coordinate.longitude)
            
            locationManager.stopUpdatingLocation()
        }

    }
    
    func locationManager(manager: CLLocationManager, didFailWithError error: NSError) {
        print(error)
    }
    
    func updateWeatherInfo(latitude:CLLocationDegrees, longitude:CLLocationDegrees) {
        let manager = AFHTTPRequestOperationManager()
        let url = "http://api.openweathermap.org/data/2.5/weather"
        let params = ["lat":latitude, "lon":longitude, "cnt":0]
        
        manager.GET(url,
            parameters: params,
            success: {(operation:
                AFHTTPRequestOperation!, responseObject: AnyObject!) in
                print("JSON:" +  responseObject.description)
                
                self.updateUISuccess(responseObject as! NSDictionary)
            },
            failure: {( operation:
                AFHTTPRequestOperation!, error:NSError!) in
                print("Error:" + error.localizedDescription)
                self.loading.text = "地理位置信息不可用"
        })
    }
    
    //set UI label
    func updateUISuccess(jsonResult:NSDictionary!) {
        self.loadingIndicator.hidden = true
        self.loadingIndicator.stopAnimating()
        self.loading.text = nil
        
        if let tempResult = jsonResult["main"]?["temp"] as? Double {
            let temperature:Double = round(tempResult - 273.15)
            let city:String = jsonResult["name"] as! String
            
            self.temperature.text = "\(temperature)˚"
            self.location.text = city
            
            let condition = (jsonResult["weather"] as! NSArray)[0]["id"] as! Int
            let sunrise = jsonResult["sys"]?["sunrise"] as! Double
            let sunset = jsonResult["sys"]?["sunset"] as! Double
            
            var nightTime = false
            let now = NSDate().timeIntervalSince1970
            
            if (now < sunrise || now > sunset) {
                nightTime = true
            }
            
            self.updateWeatherIcon(condition, nightTime: nightTime)
        } else {
//            self.loading.text = "天气信息不可用"
        }
    }
    
    //set UI image
    func updateWeatherIcon(condition: Int, nightTime: Bool) {
        if (condition < 300) {
            if nightTime {
                self.icon.image = UIImage(named: "tstorm1_night")
            } else {
                self.icon.image = UIImage(named: "tstorm1")
            }
        } else if (condition < 500) {
            self.icon.image = UIImage(named: "light_rain")
        } else if (condition < 600) {
            self.icon.image = UIImage(named: "shower3")
        } else if (condition < 700) {
            self.icon.image = UIImage(named: "snow4")
        } else if (condition < 771) {
            if nightTime {
                self.icon.image = UIImage(named: "fog_night")
            } else {
                self.icon.image = UIImage(named: "fog")
            }
        } else if (condition < 800) {
            if nightTime {
                self.icon.image = UIImage(named: "sunny_night")
            } else {
                self.icon.image = UIImage(named: "sunny")
            }
        } else if (condition < 804) {
            if nightTime {
                self.icon.image = UIImage(named: "cloudy2_night")
            } else {
                self.icon.image = UIImage(named: "cloudy2")
            }
        } else if (condition == 804) {
            self.icon.image = UIImage(named: "overcast")
        } else if ((condition >= 900 && condition < 903) || (condition > 904 && condition < 1000)) {
            self.icon.image = UIImage(named: "tstorm3")
        } else if (condition == 903) {
            self.icon.image = UIImage(named: "snow5")
        } else if (condition == 904) {
            self.icon.image = UIImage(named: "sunny")
        } else {
            self.icon.image = UIImage(named: "dunno")
        }
    }


}

